package cn.itsource.basic.interceptor;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.Constant;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.vo.UserInfo;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * spring管理
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    /**
     * 登录拦截器
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.err.println("当前请求的路径>>>>> "+ request.getRequestURI());


        //1.从请求对象request,请求头里面拿到token,如果拿不到,直接返回未登录
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)){

            //封装一个ajaxResult //"1001"
            respLoginError(response);

            return false;
        }

        //2.通过token拿到redis里面的信息,如果拿不到,同样让他去登录
        UserInfo userInfo = redisService.getKeyObjectValue(token, UserInfo.class);
        if (userInfo == null){
            respLoginError(response);

            return false;
        }
        //3. 重置登录的过期时间  之前的session自动刷新时间  redis需要手动
        redisService.setStringKeyAndValue(token, userInfo,30);
        System.out.println(">>>>>>>>>>>>>>>进入到 拦截器");
        //3.通过了 true:放行
        return true;
    }

    /**
     * 自动抽重复代码,,快捷键 alt + shift +m
     * @param response
     * @throws IOException
     */
    private void respLoginError(HttpServletResponse response) throws IOException {

        response.setContentType("application/json;charset=utf-8");

        //封装一个ajaxResult //"1001"
        AjaxResult result = AjaxResult.createError(Constant.SYSTEM_LOGIN_CODE, "给劳资去登录...");
        //响应对象响应回去失败对象
        PrintWriter writer = response.getWriter();
        writer.write(JSONObject.toJSONString(result));

    }
}
